#!/usr/bin/env python3
import os
import socket

def in_docker():
    """判断当前进程是否运行在 Docker 容器里"""
    if os.path.exists("/.dockerenv"):
        return True
    try:
        with open("/proc/1/cgroup", "rt") as f:
            content = f.read()
            if "docker" in content or "kubepods" in content or "containerd" in content:
                return True
    except Exception:
        pass
    return False

def get_container_ports():
    """获取当前容器的端口映射 (需要挂载 /var/run/docker.sock)"""
    try:
        import docker
        client = docker.DockerClient(base_url="unix:///var/run/docker.sock")
        container_id = socket.gethostname()  # 容器 ID 就是主机名
        container = client.containers.get(container_id)
        return container.attrs['NetworkSettings']['Ports']
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    if in_docker():
        print("✅ 正在容器中运行")
        ports = get_container_ports()
        print("🔌 端口映射：", ports)
    else:
        print("🖥️ 当前不在容器中运行")
